package com.team.star.ai_test;// 建议dashscope SDK的版本 >= 2.15.0

import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;// 流式输出
import org.springframework.beans.factory.annotation.Value;
// 智能体应用调用实现流式输出结果

public class Main {
    @Value("${spring.ai.dashscope.app_id}")
    private static String appId;
    @Value("${spring.ai.dashscope.api-key}")
    private static String apiKey;

    public static void streamCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量，可用百炼API Key将下行替换为：.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中，以减少API Key泄露风险。
                .apiKey(System.getenv(apiKey))
                // 替换为实际的应用 ID
                .appId(appId)
                .prompt("你是谁?")
                // 增量输出
                .incrementalOutput(true)
                .build();

        Application application = new Application();
        // .streamCall（）：流式输出内容
        Flowable<ApplicationResult> result = application.streamCall(param);
        //设置session_id: 用于多轮对话
        param.setSessionId(result.blockingFirst().getOutput().getSessionId());

        result.blockingForEach(data -> {
            //返回数据
            System.out.printf("%s\n",
                    data.getOutput().getText());
            //输出session_id
            System.out.printf("%s\n, session_id: %s\n",
                    data.getOutput().getText(), data.getOutput().getSessionId());
        });

    }


    public static void main(String[] args) {
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}


